package com.dmgis.qxfw.dataservice.cdweixin.controller;


import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.msgmediumsmallscale;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.special_srv_station;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.waterlogging_pointinfo;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.ActualElemQuery;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.CityFcstInfo;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.MsgMediumSmallScale;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.ActualData;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.DPoint;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.TownshipForecast;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.TownshipForecastKey;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.dmgis.qxfw.dataservice.cdweixin.service.WXDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.geom.Point2D;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Controller
public class WXDataServiceController {

    @Resource
    private WXDataService wx;

    @Resource
    private ITransformService transformService;
    private  final String operatingSystem;

    @Autowired
    public WXDataServiceController(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }


    @RequestMapping(value = "/getServiceData", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getServiceData(HttpServletRequest request) throws Exception {
        String result = "";
        String url = DbConfig.pg_url;
        String usr = DbConfig.pg_userName;
        String psd = DbConfig.pg_pwd;
        String method = request.getParameter("method");
        if (StringUtil.IsNullOrEmpty(method)) {
            result = "{ errors='method 不能为空'}";
            return result;
        }

        switch (method) {
            // 气象库
            case "InitSkMaxTime": {
                result = wx.InitSkMaxTime();// 区域自动站--初始化最新时间
            }
            break;
            case "loadSkCounty": {
                result = wx.loadSkCounty();// 区域自动站--加载县信息
                // //测试通过
            }
            break;
            case "loadSkStation": {
                result = wx.loadSkStation();// 区域自动站--加载站点信息
            }
            break;
            case "MultiElemQueryByTimeRange": {
                result = wx.MultiElemQueryByTimeRange(request);// 区域自动站--多要素查询(地图数据)
            }
            break;
            case "MultiElemQueryByTimeRangeSta": {
                result = wx.MultiElemQueryByTimeRangeSta(request);// 区域自动站--多要素查询（表格数据）
            }
            break;
            case "multiProductList":// 多个产品信息获取
            {
                result = wx.multiProductList(request);

            }
            break;
            case "Protection"://环保实况查询
            {
                result = wx.getProtect(url, usr, psd, request);
            }
            break;
            case "qsProtection"://环保实况查询
            {
                result = wx.getqsProtect(url, usr, psd, request);
            }
            break;
            case "SmallScaleByTimeRangeSta": {
                result = wx.SmallScaleByTimeRangeSta(request);//区域自动站--信息查询
            }
            break;
            case "InitCityMaxTime": {
                result = wx.InitCityMaxTime();// 城镇预报最新时间
            }
            break;
            case "loadCityStation": {
                result = wx.loadCityStation();// 城镇预报站点信息
            }
            break;
            case "getRainInfo":// 雨量达标统计
            {
                result = wx.getRainInfo(request);
            }
            break;
            case "ProProductList":// 常规产品信息获取
            {
                result = wx.getProProductList(url, request);

            }
            break;
            case "CityForecast": {
                result = wx.CityForecast(request);// 城镇报查询
            }
            break;
            case "CityForecastByTimeRangeSta": {
                result = wx.CityForecastByTimeRangeSta(request);// 城镇报查询
            }
            break;
            case "getmoniwaring"://获取context
            {
                result = wx.getmoniwaring(url, usr, psd, request);
            }
            break;
            case "InitFineMaxTime": {
                result = wx.InitFineMaxTime();// 精细化预报最新时间
            }
            break;
            case "SingleProduct"://最新公共服务产品查询
            {
                result = wx.getSingleProduct(request);
            }
            break;
            case "wxProductList":// 产品信息获取
            {
                result = wx.getwxProductList(url, usr, psd, request);

            }
            break;
            case "SingleWarnProduct"://预警类最新预警产品查询（地灾，山洪，森林火险 bindid）
            {
                result = wx.getSingleWarnProduct(request);
            }
            break;
            case "rainCondition"://getPicture雨量统计,雨情信息
            {
                result = wx.getrainCondition(url, usr, psd, request);
            }
            break;
            case "loadFineStation": {
                result = wx.loadFineStation();// 精细化预报站点信息
            }
            break;
            case "GetDisWeatherDayImg"://灾害性天气
            {
                String localPath ;
                if (operatingSystem.equals("Windows")){
                    localPath = request.getSession().getServletContext().getRealPath("/") + "Temp\\";// 临时文件
                }else {
                    localPath = request.getSession().getServletContext().getRealPath("/") + "Temp/";
                }

                FileUtil.mkDirs(localPath);// 创建文件夹，生成多级目录
                FileUtil.ClearTempFiles(localPath, 1000);// 清除缓存
                String distype = request.getParameter("distype");
                result = wx.GetDisWeatherDayImg(distype, localPath, request);
            }
            break;
            case "ObtainSatellite": {
                result = wx.ObtainSatellite(request);// 云图查询
            }
            break;
            case "Warning": {
                result = wx.Warning(request);// 预警信息查询
            }
            break;
            case "InitTourStation": {
                result = wx.InitTourStation(request);// 旅游气象景点信息
            }
            break;
            case "loadTourCounty": {
                result = wx.loadTourCounty();// 旅游气象景点信息
            }
            break;
            case "TourForecastSta": {
                result = wx.TourForecastSta(request);// 旅游预报信息
            }
            break;
            case "TourForecastSta_7Day": {
                result = wx.TourForecastSta_7Day(request);// 旅游预报信息
            }
            break;
            case "TourSmallScaleSta_24Hour": {
                result = wx.TourSmallScaleSta_24Hour(request);// 旅游预报信息
            }
            break;
            case "TourForecastByTimeRangeSta": {
                result = wx.TourForecastByTimeRangeSta(request);// 旅游预报信息
            }
            break;
            case "GetNewestForecastInfo":
                result = wx.GetNewestForecastInfo();
                break;
            case "FireForecast":// 森林火险预报查询
            {
                result = wx.getFireForecast(request);

            }
            break;
            case "FireForecastById":// 森林火险预报查询(地图)
            {
                result = wx.getFireForecastById(request);

            }
            break;
            case "FireHistory":// 森林火险历史
            {
                result = wx.getFireHistory(request);

            }
            break;
            case "FirePoint":// 森林火险历史
            {
                result = wx.getFirePoint(url, usr, psd, request);

            }
            break;
            case "ForestDisaster":// 病虫害
            {
                result = wx.getForestDisaster(request);

            }
            break;
            case "lyForestDisaster":// 病虫害
            {
                result = wx.getlyForestDisaster(request);

            }
            break;
            case "GetQuHuaProduct":// 农业区划图
            {
                result = wx.getQuHuaProduct(request);

            }
            break;
            case "GetNewestDisasterInfo":// 最新地灾预警
                result = wx.GetNewestDisasterInfo(request);
                break;
            case "DZWarning":// 地灾预警查询
            {
                result = wx.getDZWarning(request);

            }
            break;
            case "DZWarningById":// 地灾预警查询(地图)
            {
                result = wx.getDZWarningById(url, usr, psd, request);

            }
            break;
            case "DisType":// 地灾预警查询(地图)
            {
                result = wx.DisType();

            }
            break;
            case "IndustryQuery":// 灾点查询
            {
                result = wx.IndustryQuery(request);

            }
            break;
            case "DZPolygon"://灾面绘制
                result = wx.DzPolygon(request);
                break;

            case "InitTrafficMaxTime":// 交通气象最新时间
            {
                result = wx.InitTrafficMaxTime();
            }
            break;
            case "TrafficForcast":// 交通气象
            {
                result = wx.getTrafficForcast(request);

            }
            break;
            case "InitCityFireMaxTime":// 城市气象最新时间
            {
                result = wx.InitCityFireMaxTime();

            }
            break;
            case "CityFireStation":// 城市气象、城市火险预报站点
            {
                result = wx.loadCityFireStation();

            }
            break;
            case "CityFire":// 城市气象预报查询
            {
                result = wx.getCityFire(request);

            }
            break;
            case "CityFireByTimeRangeSta":// 城市气象预报查询
            {
                result = wx.getCityFireByTimeRangeSta(request);

            }
            break;
            case "zsCityName":// 指数信息-获取地区信息
            {
                result = wx.getZsCityName();

            }
            break;

            case "InitZhiSHuForcastMaxTime":// 指数信息最新时间
            {
                result = wx.InitZhiSHuForcastMaxTime();

            }
            break;
            case "ZsForcastByTimeRange":// 指数信息查询
            {
                result = wx.getZsForcastByTimeRange(request);

            }
            break;
            case "InitWaterLoggingMaxTime":// 城市内涝最新时间
            {
                result = wx.InitWaterLoggingMaxTime();

            }
            break;
            case "WaterLogging":// 城市内涝信息查询
            {
                result = wx.getWaterLogging(request);

            }
            break;
            case "NeiLaoForecast":// 城市内涝预报查询
            {
                result = wx.getNeiLaoForecast(request);

            }
            break;
            case "loadThunderCounty":// 雷电气象加载县信息
            {
                result = wx.loadThunderCounty();

            }
            break;
            case "shanhongyj"://山洪预警warnresult查询
            {
                result = wx.getShanhongyj(url, usr, psd, request);
            }
            break;
            case "InitThunderMaxTime":// 雷电气象最新时间
            {
                result = wx.InitThunderMaxTime();

            }
            break;
            case "Thunder":// 雷电气象信息查询
            {
                result = wx.getThunder(request);

            }
            break;
            /****************************************************************
             ********************* 农气****************************************
             *****************************************************************/

            case "ArticleType":// 文章类别
            {
                result = wx.getArticleType(request);

            }
            break;
            case "WenDang":// 获取文档
            {
                result = wx.getWenDang(request);

            }
            break;
            case "CropGrowth":// 作物发育期指标
            {
                result = wx.getCropGrowth();

            }
            break;
            case "DiseasesAndPests":// 病虫害指标
            {
                result = wx.getDiseasesAndPests();

            }
            break;
            case "WeatherDiseases":// 作物气象灾害指标
            {
                result = wx.getWeatherDiseases();

            }
            break;
            case "InitHumidMaxTime":// 农气预报--土壤墒情最新时间
            {
                result = wx.InitHumidMaxTime();

            }
            break;
            case "LoadVideo":// 农气预报--视频信息
            {
                result = wx.LoadVideo(request);

            }
            break;
            case "LoadAgriStation":// 农服站点信息
            {
                result = wx.LoadAgriStation();

            }
            break;
            case "LoadAgriMonitorInfo":// 农情监控
            {
                result = wx.LoadAgriMonitorInfo(url, usr, psd);

            }
            break;
            case "nongshiYB":// 产品信息获取
            {
                result = wx.nongshiYB(url, usr, psd, request);

            }
            break;
            case "LoadBchMonitorInfo":// 农业病虫害监控
            {
                result = wx.LoadBchMonitorInfo(url, usr, psd);

            }
            break;
            case "DaHuTongJi":// 大户统计
            {
                result = wx.getDaHuTongJi(request);

            }
            break;
            case "CropName":// 发育期--农作物名称
            {
                result = wx.getCropName(request);

            }
            break;
            case "CropVariety":// 发育期--农作物品种
            {
                result = wx.getCropVariety(request);

            }
            break;
            case "GrowthHistory":// 发育期历史表数据
            {
                result = wx.getGrowthHistory(request);

            }
            break;
            case "GrowthForcast":// 发育期预报数据
            {
                result = wx.getGrowthForcast(request);

            }
            break;
            case "CropNameInYield":// 产量--农作物名称
            {
                result = wx.getCropNameInYield(url, usr, psd, request);

            }
            break;
            case "CropVarietyInYield":// 产量--农作物品种
            {
                result = wx.getCropVarietyInYield(url, usr, psd, request);

            }
            break;
            case "GetDisProduct":// 农业风险区划图
            {
                result = wx.getDisProduct(request);

            }
            break;
            case "GetDisImg":// 农业风险区划图
            {
                result = wx.getDisImg(request);

            }
            break;
            /****************************************************************
             ********************* 电力****************************************
             *****************************************************************/
            case "rain"://雨量统计
            {
                result = wx.getrainWeather(request);
            }
            break;
            case "jdSenlinhx"://景点森林火险context查询
            {
                result = wx.getjdSenlinhx(request);
            }
            break;
            case "jtyj"://交通预警context查询
            {
                result = wx.getjtyj(request);
            }
            break;
            case "getcontext"://获取context
            {
                result = wx.getcontext(request);
            }
            break;
            case "qianshiyubao"://山洪预警warnresult查询
            {
                result = wx.getQianshiyubao(request);
            }
            break;
            case "DayProtection"://环保实况查询
            {
                result = wx.getDayProtection(request);
            }
            break;
            case "WeekProtection"://环保实况查询
            {
                result = wx.getWeekProtection(url, usr, psd, request);
            }
            break;
            case "getWXDZwarning"://获取context
            {
                result = wx.getWXDZwarning(url, usr, psd, request);
            }
            break;
            case "getStationId":// 农业大户站点Id
            {
                String town = request.getParameter("town");
                result = wx.getStationId(town);
            }
            break;
        }
        return result;
    }


    /* 得到灾点查询 */
    @RequestMapping("/getDPoint")
    @ResponseBody
    public Object getDPoint(HttpServletRequest request, Model model) throws Exception {
        DPoint selectKey = new DPoint();// 查询类
        String countys = request.getParameter("countys");//
        String types = request.getParameter("disTypes");//
        String levels = request.getParameter("levels");
        String disLevels = request.getParameter("disLevels");
        String type = request.getParameter("type");
        selectKey.setCounty(countys);
        selectKey.setDis_type(types);
        selectKey.setDis_level(levels);
        selectKey.setDanger_level(disLevels);
        Object resultList = wx.getDPoint(selectKey, type);
        return resultList;
    }

    /* 得到实况 */
    @RequestMapping("/getskPoint")
    @ResponseBody
    public Object getskPoint(HttpServletRequest request, Model model) throws Exception {
        DPoint selectKey = new DPoint();// 查询类
        String countys = request.getParameter("countys");//
        String types = request.getParameter("disTypes");//
        String levels = request.getParameter("levels");
        String disLevels = request.getParameter("disLevels");
        selectKey.setCounty(countys);
        selectKey.setDis_type(types);
        selectKey.setDis_level(levels);
        selectKey.setDanger_level(disLevels);
        List<msgmediumsmallscale> resultList = wx.getskPoint1(selectKey);
        int flag = 0;
        return resultList;
    }

    /* 得到预报 */
    @RequestMapping("/getfcstPoint")
    @ResponseBody
    public Object getfcstPoint(HttpServletRequest request, Model model) throws Exception {
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        Date nowdate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfHour = new SimpleDateFormat("HH");
        String time = simpleDateFormat.format(nowdate);
        int hour = Integer.parseInt(sdfHour.format(nowdate));
        String sc = "08";
        if (hour >= 20) {
            sc = "20";
        }
        String sx = request.getParameter("sx") == null ? "24" : request.getParameter("sx");// 时效
        String cityId = request.getParameter("cityId");// 城市
        if (cityId == null) {
            cityId = request.getParameter("staIds");
        }
        String type = request.getParameter("type");// 类型
        String county = request.getParameter("county");// 区县
        String strStationID = "";
        String strCountyName = "";
        int nTimes;
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        WebCtrlData wcd = new WebCtrlData();
        try {


            if (!(cityId == null) && !cityId.equals("")) {
                selectKey.setStationID(cityId);// 站点号
            }
            selectKey.setTimeChar(sc);
            selectKey.setDateChar(DateTime.parseDate(time).toDate());

            List<TownshipForecast> fcstList = wx.getfcstPoint1(selectKey);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i += 14) {
                strStationID = fcstList.get(i).getStationID();
                strCountyName = fcstList.get(i).getStationName();

                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = wcd.GetAllFx(String.format("%f", fcstList.get(i).getWindD())).toString();
                String windD24 = wcd.GetAllFx(String.format("%f", fcstList.get(i + 1).getWindD())).toString();

                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWindS())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWindS())));
                String windS12 = String.valueOf(fcstList.get(i).getWindS());
                String windS24 = String.valueOf(fcstList.get(i + 1).getWindS());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                    weather += fcstList.get(i).getWeather1().trim();
                } else {
                    weather += fcstList.get(i).getWeather1().trim() + "转" + fcstList.get(i + 1).getWeather1().trim();
                }
                double maxTemp = fcstList.get(i).getMaxTemp() > fcstList.get(i + 1).getMaxTemp() ? fcstList.get(i).getMaxTemp() : fcstList.get(i + 1).getMaxTemp();
                double minTemp = fcstList.get(i).getMinTemp() > fcstList.get(i + 1).getMinTemp() ? fcstList.get(i + 1).getMinTemp() : fcstList.get(i).getMinTemp();
                String pic1 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
                String pic2 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(fcstList.get(i).getDateChar());
                calendar.add(Calendar.DATE, fcstList.get(i).getNTimes() / 24);
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
                String tempdate = simpleDateFormat1.format(calendar.getTime());
                fcstInfo.setTime(tempdate);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                //
                DmMapPoint dt = new DmMapPoint();
                dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                fcstInfo.setX(dt.x);
                fcstInfo.setY(dt.y);
                fcstInfo.setTimechar(fcstList.get(i).getTimeChar());
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
                fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
                fcstInfo.setWeather(weather);
                fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                resultList.add(fcstInfo);
            }

        } catch (Exception e) {
            // TODO: 城镇预报查询异常
            e.printStackTrace();
            // log.error(e);
        }
        return resultList;
    }

    /* 得到实况，有站点绑定 */
    @RequestMapping("/getskPoint1")
    @ResponseBody
    public Object getskPoint1(HttpServletRequest request, Model model) throws Exception {
        DPoint selectKey = new DPoint();// 查询类
        String countys = request.getParameter("countys");//
        String types = request.getParameter("disTypes");//
        String levels = request.getParameter("levels");
        String disLevels = request.getParameter("disLevels");
        String[] stations = request.getParameterValues("stations[]");
        selectKey.setCounty(countys);
        selectKey.setDis_type(types);
        selectKey.setDis_level(levels);
        selectKey.setDanger_level(disLevels);
        selectKey.setStations(stations);
        List<msgmediumsmallscale> resultList = wx.getskPoint(selectKey);
        return resultList;
    }

    /* 得到实况，有站点绑定 */
    @RequestMapping("/getTownSta")
    @ResponseBody
    public Object getTownSta(HttpServletRequest request, Model model) throws Exception {
        String starttime = request.getParameter("starttime");
        String sc = request.getParameter("sc");
        String sx = request.getParameter("sx");
        Object resultList = wx.getTownSta(starttime, sc, sx);
        return resultList;
    }


    /* 得到预报，有站点绑定 */
    @RequestMapping("/getfcstPoint1")
    @ResponseBody
    public Object getfcstPoint1(HttpServletRequest request, Model model) throws Exception {
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        Date nowdate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(nowdate);
        String[] stations = request.getParameterValues("stations[]");
        String sc = "08";
        DateTime dateTime = new DateTime(nowdate);
        if (dateTime.GetHour() >= 20) {
            sc = "20";
        }
        String sx = request.getParameter("sx");// 时效
        String cityId = request.getParameter("cityId");// 城市
        String type = request.getParameter("type");// 类型
        String county = request.getParameter("county");// 区县
        String strStationID = "";
        String strCountyName = "";
        int nTimes;
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        WebCtrlData wcd = new WebCtrlData();
        try {

            if (!(cityId == null) && !cityId.equals("")) {
                selectKey.setStationID(cityId);// 站点号
            }
            selectKey.setTimeChar(sc);
            selectKey.setDateChar(DateTime.parseDate(time).toDate());

            List<TownshipForecast> fcstList = wx.getfcstPoint(selectKey, stations);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i += 14) {
                strStationID = fcstList.get(i).getStationID();
                strCountyName = fcstList.get(i).getStationName();

                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = wcd.GetAllFx(String.format("%f", fcstList.get(i).getWindD())).toString();
                String windD24 = wcd.GetAllFx(String.format("%f", fcstList.get(i + 1).getWindD())).toString();

                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWindS())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWindS())));
                String windS12 = String.valueOf(fcstList.get(i).getWindS());
                String windS24 = String.valueOf(fcstList.get(i + 1).getWindS());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                    weather += fcstList.get(i).getWeather1().trim();
                } else {
                    weather += fcstList.get(i).getWeather1().trim() + "转" + fcstList.get(i + 1).getWeather1().trim();
                }
                double maxTemp = fcstList.get(i).getMaxTemp() > fcstList.get(i + 1).getMaxTemp() ? fcstList.get(i).getMaxTemp() : fcstList.get(i + 1).getMaxTemp();
                double minTemp = fcstList.get(i).getMinTemp() > fcstList.get(i + 1).getMinTemp() ? fcstList.get(i + 1).getMinTemp() : fcstList.get(i).getMinTemp();
                String pic1 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
                String pic2 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(fcstList.get(i).getDateChar());
                calendar.add(Calendar.DATE, fcstList.get(i).getNTimes() / 24);
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
                String tempdate = simpleDateFormat1.format(calendar.getTime());
                fcstInfo.setTime(tempdate);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                //
                DmMapPoint dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                fcstInfo.setX(dt.x);
                fcstInfo.setY(dt.y);
                fcstInfo.setTimechar(fcstList.get(i).getTimeChar());
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
                fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
                fcstInfo.setWeather(weather);
                fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                resultList.add(fcstInfo);
            }

        } catch (Exception e) {
            // TODO: 城镇预报查询异常
            e.printStackTrace();
            // log.error(e);
        }
        return resultList;
    }

    /* 易涝点 */
    @RequestMapping("/getwaterlogpnt")
    @ResponseBody
    public Object getwaterlogpnt(HttpServletRequest request, Model model) {
        List<waterlogging_pointinfo> logPoints = wx.getwaterlogpnt();
        return logPoints;
    }


    /**
     * 安监初始化
     *
     * @return
     * @author dsq
     * @date 2018年6月29日
     */
    @RequestMapping("/getAnjianPoint")
    @ResponseBody
    public Object getAnjianPoint(HttpServletRequest request, Model model) {
        String staName = request.getParameter("stationName");
        List<special_srv_station> resultList = new ArrayList<special_srv_station>();
        resultList = wx.getAnjianPoint(staName);
        if (resultList != null && resultList.size() > 0) {
            for (special_srv_station srv : resultList) {
                srv.setLon(srv.getLongitude());
                srv.setLat(srv.getLatitude());
            }
        }
        return resultList;
    }

    /**
     * 预报初始化
     *
     * @return
     * @author dsq
     * @date 2018年6月29日
     */
    @RequestMapping("/AnjianYuBao")
    @ResponseBody
    public Object AnjianYuBao(HttpServletRequest request, Model model) {
        String time = request.getParameter("date").substring(0, 10);
        ;// 时间
        String sc = request.getParameter("sc");// 时次
        String sx = request.getParameter("sx");// 时效
        String r = request.getParameter("r");// 半径
        String lon = request.getParameter("lon");// 精度
        String lat = request.getParameter("lat");// 纬度
        String strStationID = "";
        String strCountyName = "";
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        WebCtrlData wcd = new WebCtrlData();
        try {

            List<TownshipForecast> fcstList = wx.getAnjianFcst(time, sc, sx, r, lon, lat);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i += 2) {
                Point2D center = new Point2D.Double(Double.parseDouble(lon), Double.parseDouble(lat));//
                Point2D yidong = new Point2D.Double(fcstList.get(i).getLongitude(), fcstList.get(i).getLatitude());
                if (getDistance(center, yidong) < Double.parseDouble(r)) {
                    strStationID = fcstList.get(i).getStationID();
                    strCountyName = fcstList.get(i).getStationName();
                    if (strCountyName.contains("乡")) {
                        strCountyName = strCountyName.substring(0, strCountyName.indexOf('乡') + 1);
                    }
                    if (strCountyName.contains("镇")) {
                        strCountyName = strCountyName.substring(0, strCountyName.indexOf('镇') + 1);
                    }
                    String weather = "";// 天气信息
                    String windD = "";// 风向信息
                    String windV = "";// 风速信息
                    String windS = "";// 风速信息
                    String windD12 = wcd.GetAllFx(fcstList.get(i).getWindD().toString().replace("-65535", "0").trim());
                    String windD24 = wcd.GetAllFx(fcstList.get(i + 1).getWindD().toString().replace("-65535", "0").trim());
                    String windV12 = String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWindS()));
                    String windV24 = String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWindS()));
                    String windS12 = String.valueOf(fcstList.get(i).getWindS());
                    String windS24 = String.valueOf(fcstList.get(i + 1).getWindS());
                    if (windD12.equals(windD24)) {
                        windD += windD12;
                    } else {
                        windD += windD12 + "转" + windD24;
                    }
                    if (windV12.equals(windV24)) {
                        windV += windV12 + "级";
                    } else {
                        windV += windV12 + "~" + windV24 + "级";
                    }
                    if (windS12.equals(windS24)) {
                        windS += windS12 + "m/s";
                    } else {
                        windS += windS12 + "~" + windS24 + "m/s";
                    }
                    if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                        weather += fcstList.get(i).getWeather1().trim();
                    } else {
                        weather += fcstList.get(i).getWeather1().trim() + "转" + fcstList.get(i + 1).getWeather1().trim();
                    }
                    double maxTemp = fcstList.get(i).getMaxTemp() > fcstList.get(i + 1).getMaxTemp() ? fcstList.get(i).getMaxTemp() : fcstList.get(i + 1).getMaxTemp();
                    double minTemp = fcstList.get(i).getMinTemp() > fcstList.get(i + 1).getMinTemp() ? fcstList.get(i + 1).getMinTemp() : fcstList.get(i).getMinTemp();
                    String pic1 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
                    String pic2 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
                    CityFcstInfo fcstInfo = new CityFcstInfo();
                    fcstInfo.setStationId(strStationID);
                    fcstInfo.setStationName(strCountyName);
                    fcstInfo.setMinTemp(minTemp);
                    fcstInfo.setMaxTemp(maxTemp);
                    fcstInfo.setRain(fcstList.get(i).getRain());
                    fcstInfo.setWindD(windD);
                    fcstInfo.setWindV(windV);
                    fcstInfo.setWindS(windS);
                    fcstInfo.setPic1(pic1);
                    fcstInfo.setPic2(pic2);
                    fcstInfo.setLat(fcstList.get(i).getLatitude());
                    fcstInfo.setLon(fcstList.get(i).getLongitude());
                    //
                    DmMapPoint dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                    fcstInfo.setX(dt.x);
                    fcstInfo.setY(dt.y);
                    fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
                    fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
                    fcstInfo.setWeather(weather);
                    fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                    resultList.add(fcstInfo);
                }
            }
        } catch (Exception e) {
            // TODO: 预报查询异常
            e.printStackTrace();
            // log.error(e);
        }
        return resultList;
    }

    /**
     * 实况初始化
     *
     * @return
     * @author dsq
     * @date 2018年6月29日
     */
    @RequestMapping("/AnjianSKInfo")
    @ResponseBody
    public Object AnjianSKInfo(HttpServletRequest request, Model model) throws ParseException {
        Date startDate = DateTime.parseDateTime(request.getParameter("startDate")).toDate();
        Date endDate = DateTime.parseDateTime(request.getParameter("endDate")).toDate();
        String element = request.getParameter("element");
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        String r = request.getParameter("r");
        ActualElemQuery elemQuery = new ActualElemQuery();
        elemQuery.setElement(element);
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        List<MsgMediumSmallScale> resultList = wx.qxElementQuery(elemQuery);
        List<ActualData> acresultList = new ArrayList<ActualData>();
        // 赋值
        try {

            if (resultList.size() > 0) {
                for (MsgMediumSmallScale data : resultList) {
                    Point2D center = new Point2D.Double(Double.parseDouble(lon), Double.parseDouble(lat));//
                    Point2D yidong = new Point2D.Double(data.getLongitude(), data.getLatitude());
                    if (getDistance(center, yidong) < Double.parseDouble(r)) {
                        ActualData actualData = new ActualData();
                        actualData.setStationId(data.getStationid().trim());
                        actualData.setStationName(data.getStationname().trim());
                        actualData.setLon(data.getLongitude());
                        actualData.setLat(data.getLatitude());
                        DmMapPoint dt = transformService.LonLatConvertToLambert(data.getLongitude(), data.getLatitude());
                        actualData.setX(dt.x);
                        actualData.setY(dt.y);
                        actualData.setRain(Double.parseDouble(String.format("%.1f", data.getRain())));
                        actualData.setTemp(Double.parseDouble(String.format("%.1f", data.getDrybulbtemp())));
                        actualData.setPressure(Double.parseDouble(String.format("%.1f", data.getStationpress())));
                        acresultList.add(actualData);
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return acresultList;
    }


    /**
     * 通过AB点经纬度获取距离
     *
     * @param pointA A点(经，纬)
     * @param pointB B点(经，纬)
     * @return 距离(单位 ： 米)
     */
    Double getDistance(Point2D pointA, Point2D pointB) {
        double EARTH_RADIUS = 6371393; // 平均半径,单位：m
        // 经纬度（角度）转弧度。弧度用作参数，以调用Math.cos和Math.sin
        double radiansAX = Math.toRadians(pointA.getX()); // A经弧度
        double radiansAY = Math.toRadians(pointA.getY()); // A纬弧度
        double radiansBX = Math.toRadians(pointB.getX()); // B经弧度
        double radiansBY = Math.toRadians(pointB.getY()); // B纬弧度
        double cos = Math.cos(radiansAY) * Math.cos(radiansBY) * Math.cos(radiansAX - radiansBX) + Math.sin(radiansAY) * Math.sin(radiansBY);
        double acos = Math.acos(cos); // 反余弦值
        return EARTH_RADIUS * acos; // 最终结果
    }
}
